import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { PurchaseService } from './purchase.service';
import { WriteInquiryComponent } from './write-inquiry/write-inquiry.component';
import { ConsultingPriceComponent } from './consulting-price/consulting-price.component';
import { IPOListComponent } from './IPO-list/IPO-list.component';
import { PurchaseListComponent } from './purchase-list/purchase-list.component';
import { FileUploadNormalComponent } from './file-upload-normal/file-upload-normal.component';
import { InquiryTempComponent } from './inquiry-template/inquiry-template.component';
import { ZQPaymentComponent } from '../zq/zq-payment/zq-payment.component';
import { ZQListComponent } from '../zq/zq-list/zq-list.component';
import { ZQListService } from '../zq/zq-list/zq-list.service';
import { PaymentComponent } from './payment-list/payment-list.component';
import { NgForm } from '@angular/forms';
import { environment } from '../../../../environments/environment';
import * as _ from 'lodash';

@Component({
  selector: 'new-stock-purchase',
  templateUrl: './purchase.component.html',
  styleUrls: ['./purchase.component.scss'],
  providers: [PurchaseService,ZQListService]
})
export class PurchaseComponent implements OnInit {
  // wizard 标签号
  public step = 1;
  
  // 列表类型（1：中签管理，2：已缴款）
  public type:any;


  // 手工到账操作下允许操作的到账状态集合
  // 例如 02(到账确认复核) 允许 到账状态为 0/9的数据进行操作
  public actionAllow = {
    "02": "0,9",
    "24": "2",
    "20": "2",
    "43": "3",
    "30": "3",
    "34": "4"
  };

  // 文件上传modal配置信息
  public fileUploadModal = {
    modalTile: "", // modal title
    title: "", // titel
    url: "", // url
    method: "", // POST OR GET
    itemAlias: "", // file alias
    formDatas: [] // POST 参数
  };

  // 发起询价
  @ViewChild(WriteInquiryComponent)
  public WriteInquiryComponent: WriteInquiryComponent;
  // 发起询价
  @ViewChild(ConsultingPriceComponent)
  public consultingPriceComponent: ConsultingPriceComponent;
  // 询价列表
  @ViewChild(IPOListComponent)
  public iPOListComponent: IPOListComponent;

  // 申购列表
  @ViewChild(PurchaseListComponent)
  public purchaseListComponent: PurchaseListComponent;

  // 中签管理
  @ViewChild("zQList")
  public zQListComponent: ZQListComponent;

  // 发起缴款
  @ViewChild(ZQPaymentComponent)
  private zQPaymentComponent: ZQPaymentComponent;

  // 缴款管理
  @ViewChild("jKList")
  public jKListComponent: ZQListComponent;

  // @ViewChild(ZQListComponent)
  // public zQListComponent: ZQListComponent;

  // // 已缴款
  // @ViewChild(PaymentComponent)
  // public paymentComponent: PaymentComponent;

  // 导入配售对象
  @ViewChild(FileUploadNormalComponent)
  private fileUploadNormalComponent: FileUploadNormalComponent;

  // 下载询价模板
  @ViewChild(InquiryTempComponent)
  private inquiryTempComponent: InquiryTempComponent;

  constructor(
    public ZQListService : ZQListService
  ) {
    this.step = 1;
  }

  ngOnInit() {
    window['$']('#purchase-wizard').wizard();
  }

  /**
   * [changeStep wizard 的选择step ]
   * @param {[type]} num [标签编号]
   */
  changeStep(num, stepName) {
    if(num==3){
      this.zQListComponent.type = 1;
      this.zQListComponent.search();
    }
    if(num==4){
      this.zQListComponent.type = 2;
      this.zQListComponent.search();
    }
    this.step = num;
  }

  /**
   * [toggleConsultingPriceModalOpen 打开录入询价modal]
   */
  toggleWriteInquiryModalOpen() {
    this.WriteInquiryComponent.openModal();
  }

  /**
   * [toggleConsultingPriceModalOpen 打开询价modal]
   */
  toggleConsultingPriceModalOpen() {
    this.consultingPriceComponent.openModal('1');
  }


  /**
   * [toggleConsultingPriceModalOpen 打开询价modal]
   */
  toggleZQPaymentModalOpen() {
    this.zQPaymentComponent.openModal();
  }


  /**
   * [toggleconfigurationSaleModalOpen 打开导入配售对象modal]
   */
  toggleconfigurationRationCodeModalOpen() {
    this.fileUploadModal = {
      modalTile: "导入配售对象",
      title: "请选择上传配售对象",
      url: environment.server + "otc/v1/Newstock/RationCode",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };
    this.fileUploadNormalComponent.openModal();
  }

  /**
   * [toggleRWModalOpen 导入入围信息]
   */
  toggleRWModalOpen() {
    this.fileUploadModal = {
      modalTile: "导入入围信息",
      title: "请选择上传入围信息",
      url: environment.server + "otc/v1/Newstock/RWList",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };

    this.fileUploadNormalComponent.openModal();
  }

  /**
   * [toggleZQModalOpen 导入中签]
   */
  toggleZQModalOpen() {
    this.fileUploadModal = {
      modalTile: "导入中签信息",
      title: "请选择中签信息",
      url: environment.server + "otc/v1/Newstock/ZQList",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };

    this.fileUploadNormalComponent.openModal();
  }

  // 导出询价指令模板
  exportNewStockInquiryExcel() {
    var path = 'otc/v1/Newstock/NewStockInquiryExcel';
    var data = _.filter(this.iPOListComponent.newStockList, { isChecked: true });
    if (data.length === 0) {
      return window["swal"]("提示", "请选择一行数据进行操作", "info");
    }
    var idArr = [];

    data.forEach(item => {
      idArr.push(item.vcNewstockId);
    });
    const $ = window["$"];
    // TODO 下载文件使用iframe的标签，临时解决方案。
    const iframe = $("<iframe id='downloadiframe'>");   // 定义一个iframe
    iframe.attr('style', 'display:none');
    iframe.attr('src', environment.server + path + '?token=' + sessionStorage.getItem('username') + "&newStockIdList=" + idArr.join());
    $('body').append(iframe);  // 将iframe放置在web中
    setTimeout("$('#downloadiframe').remove()", 5000);
  }

  // 询价模板下载
  public exportInquiryListFile() {
    var path = 'otc/v1/Newstock/InquiryListFile/';
    var data: any = _.filter(this.iPOListComponent.newStockList, { isChecked: true });
    if (data.length === 0 || data.length > 1) {
      return window["swal"]("提示", "请选择一行数据进行操作", "info");
    }
    const $ = window["$"];
    // TODO 下载文件使用iframe的标签，临时解决方案。
    const iframe = $("<iframe id='downloadiframe'>");   // 定义一个iframe
    iframe.attr('style', 'display:none');
    iframe.attr('src', environment.server + path + data[0].lNewstockNo + '?token=' + sessionStorage.getItem('username'));
    $('body').append(iframe);  // 将iframe放置在web中
    setTimeout("$('#downloadiframe').remove()", 5000);
  }

  /**
   * [toggleInquiryTempModalOpen 下载询价模板]
   */
  public toggleInquiryTempModalOpen() {
    this.inquiryTempComponent.openModal();
  }

  /**
   * 
   * @param number 中签编号
   * @param $event dom对象
   */
  public markZQHandle(zqFlag,$event){
    const that = this;
    const remittance = _.filter(that.zQListComponent.remittanceList, {isChecked: true});

    if (remittance.length === 0) {
      window["swal"]("提示", "请选择一条数据进行操作", "info");
    } else {
      // param 查询参数对象
      const param = that.zQListComponent.getDataToMarkZQHandle(remittance, zqFlag);
      // 如果是标记未中签操作
      if (zqFlag === '0') {
        // 遍历查询参数对象，判断matchResult（指令及中签比对）是否是未中签，如果不是不允许操作.
        for (let i = 0; i < param.matchResult.length; i++) {
          if (param.matchResult[i] !== '0') {
            window["swal"]("提示", `只有未中签的数据才能进行${$event.target.textContent}操作！`, "warning");
            return false;
          }
        }
      }
      // 如果是撤销标记未中签操作
      if (zqFlag !== '0') {
        for (let i = 0; i < param.matchResult.length; i++) {
          if (param.matchResult[i] === '0') {
            window["swal"]("提示", `只有标记未中签的数据才能进行${$event.target.textContent}操作！`, "warning");
            return false;
          }
        }
      }
      that.ZQListService.markZQHandle(param).subscribe(result => {
        if (result) {
          window["swal"]("提示", `${$event.target.textContent}成功`, "success");
          that.zQListComponent.refleshCurrPage();
        }
      });
    }
  }

  /**
   * [transferMoney 发起缴款
   * 1.对选择的发起缴款
   * 2.对当天缴款日发起缴款
   * 3.对当天缴款日上交所发起缴款
   * 4.对当天缴款日深交所发起缴款]
   */
  transferMoney() {
    // 是否有选中数据
    const checkedObj = _.filter(this.zQListComponent.remittanceList, { isChecked: true });

    if (checkedObj.length > 0) {
      this.zQPaymentComponent.transferMoney(checkedObj, null, null);
    } else {
      this.toggleZQPaymentModalOpen();
    }
  }

  /**
   * [toggleDZModalOpen 到账确认]
   */
  toggleDZModalOpen() {
    // 配置导入文件信息
    this.fileUploadModal = {
      modalTile: "导入到账文件",
      title: "请选择上传的到账文件",
      url: environment.server + "otc/v1/Newstock/DZList",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };

    this.fileUploadNormalComponent.openModal();
  }


  /**
   * [toggleconfigurationSaleModalOpen 打开导入询价modal]
   */
  toggleconfigurationSaleModalOpen() {
    // 配置导入文件信息
    this.fileUploadModal = {
      modalTile: "导入询价",
      title: "请选择上传询价",
      url: environment.server + "otc/v1/Newstock/InquiryList",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };
    this.fileUploadNormalComponent.openModal();
  }

  /**
   * [goZQHistory 缴款管理历史交易]
   */
  goZQHistory() {
    // 重置查询条件
    this.zQListComponent.resetSearch();
    // 查询历史
    this.zQListComponent.searchBody.isHisData = true;
    const data = {
      isHisData: true
    };
    this.zQListComponent.getRemittanceList(data);
  }

  /**
   * [backJK 缴款管理返回非历史页面]
   */
  backZQ() {
    // 重置查询条件
    this.zQListComponent.resetSearch();
    // 查询历史
    this.zQListComponent.searchBody.isHisData = false;
    const data = {
      isHisData: false
    };
    this.zQListComponent.getRemittanceList(data);
  }

  /**
   * [downloadFile downloadPaymentFile]
   */
  downloadPaymentFile() {
    const fileHref = environment.server + "otc/v1/Newstock/ExportSureFile?isHisData=false&vcFundCode&traceDate&vcNewstockId"
      + "&token=" + sessionStorage.getItem('username');
    window.location.href = fileHref;
  }

  /**
   * 手工到账确认通用函数
   * param [{
	 * 		action: 手工到账操作编号,
   *    $event: 点击的DOM对象
	 * }]
   */
  manualTransferredConfirm(action, $event) {
    const that = this;
    const remittance = _.filter(this.zQListComponent.remittanceList, {isChecked: true});
    if (remittance.length === 0) {
      window["swal"]("提示", "请选择一条数据进行操作！", "info");
    } else {
      // param 查询参数对象
      const param = this.zQListComponent.getDataToTransferredConfirm(remittance, action);
      const validate = that.validateTransferredConfirm(param);
      if(validate.message!==""){
        window["swal"]("提示", validate.message, "warning");
      }
      if(validate.isPass){
        this.ZQListService.manualTransferredConfirm(param).subscribe(result => {
          if (result) {
            window["swal"]("提示", `${$event.target.textContent}成功`, "success");
          }
          that.zQListComponent.refleshCurrPage();
        });
      }
    }
  }

  /**
   * 校验数据是否符合手工到账确认资格
   * @param data 需要检测的数据
   */
  validateTransferredConfirm(data){
    const answer = {
      isPass: false,
      message:""
    }
    const action = data.action;
    if(data.length === 0){
      answer.message = "请选择一行数据进行操作！";
      return answer;
    }
    for (let i=0; i<data.cDzStatus.length;i++ ) {
      if(!this.actionAllow[action].includes(data.cDzStatus[i])){
        if(action === "02"){
          answer.message = "只有未到账或到账异常的数据，才能进行到账确认复核操作！";
          return answer;
        }
        if(action === "20"){
          answer.message = "只有到账确认待复核的数据，才能进行驳回到账确认复核操作！";
          return answer;
        }
        if(action === "24"){
          answer.message = "只有到账确认待复核的数据，才能进行通过到账确认复核操作！";
          return answer;
        }
        if(action === "34"){
          answer.message = "只有手工到账的数据，才能进行撤销到账复刻操作！";
          return answer;
        }
        if(action === "43"){
          answer.message = "只有已撤销到账待复核的数据，才能进行通过撤销到账复核操作！";
          return answer;
        }
        if(action === "30"){
          answer.message = "只有已撤销到账待复核的数据，才能进行驳回撤销到账复核操作！";
          return answer;
        }
      }
      if(action === "24"){
        if(data.vcDzUser[i] === sessionStorage.getItem('username')){
          answer.message = "到账确认复核与通过到账确认复核不能是同一个用户操作！";
          return answer;
        }
      }
    }
    if(answer.message === "") {
      answer.isPass = true;
    }
    return answer;
  }

  /**
   * [reflesh 刷新]
   * @param {[type]} $event [是否需要刷新当前页面]
   */
  reflesh($event) {
    if ($event) {
      this.iPOListComponent.reflesh($event);
      this.purchaseListComponent.reflesh($event);
      // this.paymentComponent.reflesh($event);
      this.zQListComponent.reflesh();
    }
  }
}
